package com.immunology.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.immunology.database.ConnectionManager;
import com.immunology.model.MappingPages;

public class AddSyndromeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public AddSyndromeServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		getServletContext().getRequestDispatcher(MappingPages.ADD_SYNDROME_JSP)
				.forward(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		ConnectionManager connectionManager = new ConnectionManager();
		Connection connection = connectionManager.getConnection();
		String syndrome = request.getParameter("syndrome").toString();
		try {
			String sql = "INSERT INTO syndrome VALUES(?,?)";
			PreparedStatement statement = connection.prepareStatement(sql);
			statement.setInt(1, getId(connection));
			statement.setString(2, syndrome);
			@SuppressWarnings("unused")
			int set = statement.executeUpdate();
			statement.close();
			connectionManager.closeConnection(connection);
			request.getRequestDispatcher(MappingPages.ADD_SYNDROME_JSP)
					.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connectionManager.closeConnection(connection);
			}
		}

	}

	private int getId(Connection connection) throws SQLException {
		int id = 0;
		String sql = "SELECT * FROM syndrome";
		java.sql.Statement statement = connection.createStatement();
		java.sql.ResultSet set = statement.executeQuery(sql);
		while (set.next()) {
			id = set.getInt(1);
		}
		statement.close();
		set.close();
		return ++id;
	}

}
